package com.cai.server;

import com.cai.entity.UserSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@Slf4j
@ServerEndpoint("/server/{username}")
public class WebSocketServer {
    //CopyOnWriteArraySet 线程安全的HashSet 使用读多写少场景
    private static final Set<UserSession> clients = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        UserSession userSession = new UserSession(session, username);
        clients.add(userSession);

        for (UserSession client : clients) {
            if (!client.getSession().equals(session)) {
                client.getSession().getAsyncRemote().sendText(username+"加入连接，当前在线人数" + clients.size());
            }
        }

        log.debug(username+"加入连接，当前在线人数" + clients.size());
    }

    @OnClose
    public void onClose(Session session,@PathParam("username") String username) {
        int ONLINE_COUNT = clients.size() - 1;
        //退出连接时候给其他人发消息谁退出链接  退出前发送消息
        for (UserSession client : clients) {
            //如果集合中的session不等于当前session
            if (!client.getSession().equals(session)) {
                //当前session给其他session发送退出的消息
                client.getSession().getAsyncRemote().sendText(username+"退出连接，当前在线人数" + ONLINE_COUNT);
            }
        }

        //遍历集合 如果集合中客户端session等于当前session就删除
        clients.removeIf(client -> Objects.equals(client.getSession().getId(), session.getId()));

        log.debug(username+"退出连接，当前在线人数" + ONLINE_COUNT);
    }

    @OnMessage
    public void onMessage(Session session, String message){
        String username = null;
        for (UserSession client : clients) {
            if (client.getSession().equals(session)) {
                username = client.getUsername();
                //服务端记录数据
                log.info(username + "：{}", message);
            }
        }

        //发送消息给其他的客户端
        for (UserSession client : clients) {
            //如果集合中的session不等于当前的session   服务端接收心跳消息，但是不发送给客户端
            if (!client.getSession().equals(session)&&!message.equals("heartbeat")) {
                //给集合中的session发送消息
                client.getSession().getAsyncRemote().sendText(username + ": " + message);
            }
        }

    }

}
